package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeoutOrder() {
        log.info("定时处理超时订单： {}" , LocalDateTime.now());
//        select * from orders where status = 1 and order_time < (当前时间-15分钟);
       List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
       //把超时订单取消
       if (ordersList != null && ordersList.size() > 0){
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("支付超时，取消订单");
               orders.setCancelTime(LocalDateTime.now());
               orderMapper.update(orders);
           }
       }
    }

    @Scheduled(cron = "0 0 1 * * ?")//每日1点执行一次
    public void processDeliverOrder () {
        log.info("定时处理处于派送状态的订单： {}" , LocalDateTime.now());
        //传状态为派送中，时间为一小时前的订单
       List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusMinutes(60));
       if (ordersList != null && ordersList.size() > 0){
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.COMPLETED);
               orderMapper.update(orders);
           }
       }

    }
}














